package com.baidu.bas.upms.util;

import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

import static com.baidu.bas.upms.constant.EruptReqHeaderConst.ERUPT_HEADER_TOKEN;

/**
 * @author liuzhenchuan@foxmail.com
 * @date 2021/1/12
 */
public class RequestUtils {

    /**
     * 兼容多种认证的token类型
     */
    static final String[] secretParams = new String[]{ERUPT_HEADER_TOKEN,"Authorization","X-Access-Token"};

    public static String getSecretHeaderValue(HttpServletRequest request){
        Optional<String> optional = Arrays.stream(secretParams).filter(it -> {
            return StringUtils.isNotBlank(request.getHeader(it));
        }).findFirst();
        return optional.map(request::getHeader).orElse(null);
    }

    public static Map<String,String> getHeaders(HttpServletRequest request){
        Enumeration<String> headerNames = request.getHeaderNames();
        Map<String,String> headers = new LinkedHashMap<>();
        while (headerNames.hasMoreElements()) {
            String headerName = headerNames.nextElement();
            String headerValue = request.getHeader(headerName);
            headers.put(headerName,headerValue);
        }
        return headers;
    }

}
